package com.scpii.universal.struts.manage;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.scpii.universal.action.BaseAction;
import com.scpii.universal.util.FileUploadUtil;

@Controller
@Scope("prototype")
public class UploadFileAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private File fileInput;
	private String fileInputFileName;// Struts2的拦截器FileUploadInterceptor根据请求对象中参数"fileInput"来自行生产的一个固有属性

	public File getFileInput() {
		return fileInput;
	}

	public void setFileInput(File fileInput) {
		this.fileInput = fileInput;
	}

	public String getFileInputFileName() {
		return fileInputFileName;
	}

	public void setFileInputFileName(String fileInputFileName) {
		this.fileInputFileName = fileInputFileName;
	}

	/**
	 * 上传文件至temp目录
	 */
	public String uploadFile() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("utf-8");
		String savePath = getWebAppsRealPath() + "WORKDIR"+File.separator+"TEMP" +File.separator;
		List items = getBatchResFromRequest(savePath);
		FileItem item = null;
		String fileName = null;
		StringBuffer result = new StringBuffer();
		String format = null;
		for (int i = 0 ;i < items.size(); i++){
			item = (FileItem) items.get(i);
			// 保存文件
			if (!item.isFormField() && item.getName().length() > 0) {
				format = FilenameUtils.getExtension(item.getName());
				fileName = FileUploadUtil.generateIconName() + "."+ format;
				item.write(new File(savePath + fileName));
				result.append(item.getName()+":"+ "WORKDIR/TEMP/" + fileName + ":" + format);
			}
		}
		jsonOut(result.toString());
		return null; 
	}
}